package com.pangu.export.service;

import com.pangu.export.dto.TableColumnDto;
import com.pangu.export.entity.TableColumn;
import com.pangu.export.utils.ExcelWriteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.hibernate.validator.internal.util.privilegedactions.GetResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ExcelService {

    /**
     * 创建多表结构
     */
    public void createTableColumnExcel(Map<String, List<TableColumn>> map, TableColumnDto tableColumnDto)
            throws Exception {
        if (StringUtils.isEmpty(tableColumnDto.getExcelFileName())) {
            throw new Exception("未输入导出文件名");
        } else {
            File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
            tableColumnDto.setExcelFileName(desktopDir + "/" + tableColumnDto.getExcelFileName() + ".xlsx");
        }

        String[] header = tableColumnDto.getExcelTitle();
        Workbook wb = ExcelWriteUtil.writeExcel
                ("结构页", GetResource.class.getClassLoader().getResource("template/template_excel.xlsx").getPath(), ".xlsx", "数据库结构表", header, map, TableColumn.class);

        // 导入指定地址的Excel
        OutputStream os = new FileOutputStream(tableColumnDto.getExcelFileName());
        wb.write(os);
        os.close();
    }
}
